﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AudioCore.Biz;
using AudioCore.Entity;
//using System.Drawing;
using Skywi.Common.Entity;
using System.IO;
using AudioBookWS.ServiceUtil;
using System.Text.RegularExpressions;
using AudioBook.AudioManagement.Util;
using System.Collections;
using WMPLib;

namespace AudioBook.AudioManagement.AudioManage
{
    public partial class ArticleDetail : System.Web.UI.Page
    {
        #region Fields & constants
        const int MAX_TIME = 30000;
        CategoryBiz bizCategory = new CategoryBiz();
        CategoryArticleBiz bizCategoryArticle = new CategoryArticleBiz();
        ArticleBiz bizArticle = new ArticleBiz();
        ArticlePartBiz bizArticlePart = new ArticlePartBiz();

        List<CategoryArticleEntity> lstCategoryArticle = new List<CategoryArticleEntity>();
        #endregion Fields & constants

        #region Private methods

        private void LoadData()
        {
            LoadArticleInfo();

            LoadCategory();

            LoadArticlePart();
        }

        private void LoadArticleInfo()
        {
            ArticleEntity enArticle = bizArticle.GetArticleByID(int.Parse(hidArticleID.Value));
            if (enArticle == null)
            {
                Response.Redirect(GUIConstants.WebPage.AudioPage.DefaultAudio);
            }
            else
            {
                lblArticleName.Text = enArticle.ArticleName;
            }
        }

        private void LoadCategory()
        {
            List<CategoryArticleEntity> lstCatTemp = bizCategoryArticle.GetMappingCategoryArticle(int.Parse(hidArticleID.Value));
            lstCatTemp.Sort(delegate(CategoryArticleEntity en1, CategoryArticleEntity en2) { return en2.SortOrder.CompareTo(en1.SortOrder); });

            ProcessCategory(lstCatTemp, 0, string.Empty);
            gridCategory.DataSource = lstCategoryArticle;
            gridCategory.DataBind();
        }

        private void ProcessCategory(List<CategoryArticleEntity> lstParent, int parentID, string space)
        {
            List<CategoryArticleEntity> lstChild = lstParent.Where(item => item.ParentID == parentID).ToList<CategoryArticleEntity>();
            foreach (CategoryArticleEntity item in lstChild)
            {
                item.CategoryName = space + item.CategoryName;
                lstCategoryArticle.Add(item);
                ProcessCategory(lstParent, item.CategoryID, space + "---+");
            }
        }

        private void LoadArticlePart()
        {
            int articleID = int.Parse(hidArticleID.Value);
            List<ArticlePartEntity> lstArticlePart = bizArticlePart.GetArticlePartByArticleID(articleID);
            lstArticlePart.Sort(delegate(ArticlePartEntity en1, ArticlePartEntity en2) { return en2.SortOrder.CompareTo(en1.SortOrder); });
            gridArticlePart.DataSource = lstArticlePart;
            gridArticlePart.DataBind();
        }

        #endregion Private methods

        #region Event handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string strID = Request.QueryString[GUIConstants.Common.ID_QUERY];
                int intValue;
                if (!string.IsNullOrEmpty(strID) && !string.IsNullOrEmpty(strID.Trim()) && int.TryParse(strID, out intValue))
                {
                    hidArticleID.Value = intValue.ToString();
                    hplEdit.NavigateUrl = string.Format(GUIConstants.WebPage.AudioPage.EditArticle, intValue);
                    LoadData();
                }
                else
                {
                    //Response.Redirect(GUIConstants.WebPage.VideoPage.DefaultVideo);
                }
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.Url.ToString());
        }

        protected void gridCategory_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                CategoryArticleEntity enCategoryArticle = (CategoryArticleEntity)e.Item.DataItem;

                Label lblOrder = (Label)e.Item.FindControl("lblOrder");
                lblOrder.Text = (e.Item.ItemIndex + 1).ToString();

                HiddenField hidCategoryID = (HiddenField)e.Item.FindControl("hidCategoryID");
                hidCategoryID.Value = enCategoryArticle.CategoryID.ToString();

                HiddenField hidCategoryArticleID = (HiddenField)e.Item.FindControl("hidCategoryArticleID");
                hidCategoryArticleID.Value = enCategoryArticle.CategoryArticleID.ToString();

                HyperLink hplName = (HyperLink)e.Item.FindControl("hplName");
                hplName.Text = enCategoryArticle.CategoryName;
                if (enCategoryArticle.ParentID != 0)
                {
                    hplName.NavigateUrl = string.Format(GUIConstants.WebPage.CategoryPage.EditCategory, enCategoryArticle.CategoryID);
                }

                ImageButton btnActive = (ImageButton)e.Item.FindControl("btnActive");
                btnActive.ImageUrl = enCategoryArticle.ArticleID == 0 ? GUIConstants.Icon.FalseIcon : GUIConstants.Icon.TrueIcon;
                btnActive.CommandName = GUIConstants.EventCommand.smx_ChangeActive;

                Label lblCategoryArticleID = (Label)e.Item.FindControl("lblCategoryArticleID");
                lblCategoryArticleID.Text = enCategoryArticle.CategoryArticleID.ToString();
            }
        }

        protected void gridCategory_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case GUIConstants.EventCommand.smx_ChangeActive:
                    HiddenField hidCategoryArticleID = (HiddenField)e.Item.FindControl("hidCategoryArticleID");
                    int categoryArticleID = int.Parse(hidCategoryArticleID.Value);
                    if (categoryArticleID != 0)
                    {
                        bizCategoryArticle.DeleteCategoryArticle(categoryArticleID);
                    }
                    else
                    {
                        HiddenField hidCategoryID = (HiddenField)e.Item.FindControl("hidCategoryID");
                        int categoryID = int.Parse(hidCategoryID.Value);
                        CategoryArticleEntity enCategoryArticle = new CategoryArticleEntity();
                        enCategoryArticle.CategoryID = categoryID;
                        enCategoryArticle.ArticleID = int.Parse(hidArticleID.Value);
                        enCategoryArticle.SortOrder = DateTime.Now;
                        bizCategoryArticle.AddCategoryArticle(enCategoryArticle);
                    }
                    break;
            }

            LoadCategory();
        }

        protected void btnSaveArticlePart_Click(object sender, EventArgs e)
        {
            foreach (DataGridItem item in gridArticlePart.Items)
            {
                HiddenField hidPartName = (HiddenField)item.FindControl("hidPartName");
                HiddenField hidSortOrder = (HiddenField)item.FindControl("hidSortOrder");
                HiddenField hidPrice = (HiddenField)item.FindControl("hidPrice");

                TextBox txtName = (TextBox)item.FindControl("txtName");
                TextBox txtSortOrder = (TextBox)item.FindControl("txtSortOrder");

                if (!hidPartName.Value.Equals(txtName.Text)
                    || int.Parse(hidSortOrder.Value) != int.Parse(txtSortOrder.Text))
                {
                    HiddenField hidArticlePartID = (HiddenField)item.FindControl("hidArticlePartID");
                    ArticlePartEntity enArticlePart = bizArticlePart.GetArticlePartByID(int.Parse(hidArticlePartID.Value));
                    if (enArticlePart != null)
                    {
                        enArticlePart.ArticlePartName = txtName.Text;
                        enArticlePart.SortOrder = int.Parse(txtSortOrder.Text);
                        bizArticlePart.UpdateArticlePart(enArticlePart);
                    }
                }
            }

            LoadArticlePart();
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            string strDir = GlobalParam.DataFolder + AudioCore.Common.Constant.AUDIO_FOLDER + hidArticleID.Value + "\\";

            foreach (DataGridItem item in gridArticlePart.Items)
            {
                CheckBox chkSelected = (CheckBox)item.FindControl("chkSelected");
                if (chkSelected.Checked)
                {
                    HiddenField hidArticlePartID = (HiddenField)item.FindControl("hidArticlePartID");

                    string filePattent = hidArticlePartID.Value + "_*.mp3";

                    if (Directory.Exists(strDir))
                    {
                        string[] arrFile = Directory.GetFiles(strDir, filePattent);
                        foreach (string strFile in arrFile)
                        {
                            try
                            {
                                File.Delete(strFile);
                            }
                            catch (Exception ex)
                            {
                                valCommon.IsValid = false;
                                valCommon.ErrorMessage = ex.Message;
                                return;
                            }
                        }
                    }
                    bizArticlePart.DeleteArticlePart(int.Parse(hidArticlePartID.Value));
                }
            }
            LoadArticlePart();
        }

        protected void gridArticlePart_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                ArticlePartEntity enArticle = (ArticlePartEntity)e.Item.DataItem;

                Label lblOrder = (Label)e.Item.FindControl("lblOrder");
                lblOrder.Text = (e.Item.ItemIndex + 1).ToString();

                HiddenField hidArticlePartID = (HiddenField)e.Item.FindControl("hidArticlePartID");
                hidArticlePartID.Value = enArticle.ArticlePartID.ToString();

                HiddenField hidPartName = (HiddenField)e.Item.FindControl("hidPartName");
                hidPartName.Value = enArticle.ArticlePartName;

                HiddenField hidSortOrder = (HiddenField)e.Item.FindControl("hidSortOrder");
                hidSortOrder.Value = enArticle.SortOrder.ToString();

                TextBox txtName = (TextBox)e.Item.FindControl("txtName");
                txtName.Text = enArticle.ArticlePartName;

                TextBox txtSortOrder = (TextBox)e.Item.FindControl("txtSortOrder");
                txtSortOrder.Text = enArticle.SortOrder.ToString();

                Label lblSize = (Label)e.Item.FindControl("lblSize");
                lblSize.Text = enArticle.FileSize.ToString();

                Label lblDuration = (Label)e.Item.FindControl("lblDuration");
                lblDuration.Text = enArticle.Duration.ToString();

                Label lblPartCounter = (Label)e.Item.FindControl("lblPartCounter");
                lblPartCounter.Text = enArticle.PartCounter.ToString();

                Label lblCreatedDateTime = (Label)e.Item.FindControl("lblCreatedDateTime");
                lblCreatedDateTime.Text = enArticle.CreatedDateTime.ToString(GUIConstants.Common.DATE_TIME_FORMAT);

                Label lblArticlePartID = (Label)e.Item.FindControl("lblArticlePartID");
                lblArticlePartID.Text = enArticle.ArticlePartID.ToString();

                ImageButton btnPlay = (ImageButton)e.Item.FindControl("btnPlay");
                string playUrl = string.Format(GUIConstants.WebPage.AudioPage.PlayAudio, enArticle.ArticlePartID);
                //btnPlay.OnClientClick = string.Format("PopupCenter('{0}', 'Testing audio', 300, 300)", playUrl);
                btnPlay.OnClientClick = string.Format("window.open('{0}','windowName','width=320, height=320'); return false;", playUrl);
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                ImageButton btnNewPart = (ImageButton)e.Item.FindControl("btnNewPart");
                btnNewPart.CommandName = GUIConstants.EventCommand.smx_AddNew;
            }
        }

        protected void gridArticlePart_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case GUIConstants.EventCommand.smx_AddNew:
                    Regex rgMp3 = new Regex("\\.mp3$", RegexOptions.IgnoreCase);
                    TextBox txtPartName = (TextBox)e.Item.FindControl("txtPartName");
                    TextBox txtAudioFile = (TextBox)e.Item.FindControl("txtAudioFile");

                    string srcFile = GlobalParam.RootFileFolder + txtAudioFile.Text;
                    if (!File.Exists(srcFile) || !rgMp3.IsMatch(srcFile))
                    {
                        valCommon.IsValid = false;
                        valCommon.ErrorMessage = "Audio file not invalid or not exist.";
                        return;
                    }
                    else
                    {
                        #region Insert article part

                        int intValue = 0;

                        ArticlePartEntity enArticlePart = new ArticlePartEntity();
                        enArticlePart.ArticleID = int.Parse(hidArticleID.Value);
                        enArticlePart.ArticlePartName = txtPartName.Text;

                        FileInfo f = new FileInfo(srcFile);
                        enArticlePart.FileSize = f.Length;

                        WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
                        IWMPMedia mediaInfo = wmp.newMedia(srcFile);
                        enArticlePart.Duration = (int)mediaInfo.duration;

                        enArticlePart.PartCounter = 1;
                        //int maxTime = MAX_TIME;
                        //if (enArticlePart.Duration % maxTime == 0)
                        //{
                        //    enArticlePart.PartCounter = enArticlePart.Duration / maxTime;
                        //}
                        //else
                        //{
                        //    enArticlePart.PartCounter = enArticlePart.Duration / maxTime + 1;
                        //}

                        enArticlePart.DownloadCounter = 0;

                        if (gridArticlePart.Items.Count > 0)
                        {
                            DataGridItem firstItem = gridArticlePart.Items[0];
                            HiddenField hidSortOrder = (HiddenField)firstItem.FindControl("hidSortOrder");
                            enArticlePart.SortOrder = int.Parse(hidSortOrder.Value) + 1;
                        }
                        else
                        {
                            enArticlePart.SortOrder = 0;
                        }
                        enArticlePart.FileStatus = (int)AudioCore.Common.Constant.FileStatus.Added;
                        enArticlePart.CreatedDateTime = DateTime.Now;
                        int result = bizArticlePart.AddArticlePart(enArticlePart);

                        if (result == 0)
                        {
                            valCommon.IsValid = false;
                            valCommon.ErrorMessage = GUIConstants.ErrorMessage.TransactionError;
                            return;
                        }

                        #endregion

                        #region Splip audio file

                        //int articlePartID 
                        string desFolder = GlobalParam.DataFolder + AudioCore.Common.Constant.AUDIO_FOLDER + hidArticleID.Value + "\\";
                        string desFile = desFolder + result.ToString() + "_000" + AudioCore.Common.Constant.AUDIO_EXTENSION;

                        if (!Directory.Exists(desFolder))
                        {
                            Directory.CreateDirectory(desFolder);
                        }

                        File.Copy(srcFile, desFile, true);

                        //ArrayList arrSplitFile = AudioBookUtility.Split(desFile, desFolder, maxTime);

                        //int i = 0;

                        //foreach (string strFile in arrSplitFile)
                        //{
                        //    i++;
                        //    string buffer = i >= 100 ? string.Empty : (i >= 10 ? "0" : "00");

                        //    string desBlock = desFolder + result.ToString() + "_" + buffer + i.ToString() + AudioCore.Common.Constant.AUDIO_EXTENSION;
                        //    if (!File.Exists(desBlock))
                        //    {
                        //        File.Move(strFile, desBlock);
                        //    }
                        //}

                        #endregion
                    }
                    break;
            }

            LoadArticlePart();
        }

        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            CommandEventArgs command = (CommandEventArgs)args;

            switch (command.CommandName)
            {
                case GUIConstants.EventCommand.smx_ShowPopup:
                    popupAddProject.Show();
                    break;

                case GUIConstants.EventCommand.MoveArticlePart:
                    int newArticleID = int.Parse(command.CommandArgument.ToString());

                    if (newArticleID == int.Parse(hidArticleID.Value))
                    {
                        break;
                    }

                    string oldFolder = GlobalParam.DataFolder + AudioCore.Common.Constant.AUDIO_FOLDER + hidArticleID.Value + "\\";
                    string newFolder = GlobalParam.DataFolder + AudioCore.Common.Constant.AUDIO_FOLDER + newArticleID + "\\";

                    if (!Directory.Exists(newFolder))
                    {
                        Directory.CreateDirectory(newFolder);
                    }

                    foreach (DataGridItem item in gridArticlePart.Items)
                    {
                        CheckBox chkSelected = (CheckBox)item.FindControl("chkSelected");

                        if (chkSelected.Checked)
                        {
                            HiddenField hidArticlePartID = (HiddenField)item.FindControl("hidArticlePartID");

                            ArticlePartEntity enArticlePart = bizArticlePart.GetArticlePartByID(int.Parse(hidArticlePartID.Value));
                            if (enArticlePart != null)
                            {
                                enArticlePart.ArticleID = newArticleID;
                                int result = bizArticlePart.UpdateArticlePart(enArticlePart);
                                if (result != 0)
                                {
                                    string filePattern = string.Format("{0}_*", hidArticlePartID.Value);

                                    string[] oldFiles = Directory.GetFiles(oldFolder, filePattern);
                                    foreach (string oldFile in oldFiles)
                                    {
                                        string newFile = newFolder + AudioCore.Common.Utility.GetFileName(oldFile);
                                        File.Move(oldFile, newFile);
                                    }
                                }
                            }
                        }
                    }

                    Response.Redirect(Request.Url.ToString());

                    break;
            }

            return true;
        }

        #endregion Event handlers
    }
}
